package service

import (
	"context"
	v1 "server_go/api/v1"
	"server_go/internal/repository"
)

type TagService interface {
	GetTags(ctx context.Context) ([]v1.ReadtagResponse, error)
	CreateTag(ctx context.Context, req v1.CreateTagRequest) error
	DeleteTag(ctx context.Context, tagId uint) error
}

func NewTagService(
	service *Service,
	tagRepository repository.TagRepository,
	articleRepository repository.ArticleRepository,
) TagService {
	return &tagService{
		Service:           service,
		tagRepository:     tagRepository,
		articleRepository: articleRepository,
	}
}

type tagService struct {
	*Service
	tagRepository     repository.TagRepository
	articleRepository repository.ArticleRepository
}

func (s *tagService) GetTags(ctx context.Context) ([]v1.ReadtagResponse, error) {
	tags, err := s.tagRepository.GetTags(ctx)
	if err != nil {
		return nil, err
	}
	var readtagResponse []v1.ReadtagResponse
	for _, tag := range tags {
		readtagResponse = append(readtagResponse, v1.ReadtagResponse{
			ID:   tag.ID,
			Name: tag.Name,
		})
	}
	return readtagResponse, nil

}
func (s *tagService) CreateTag(ctx context.Context, req v1.CreateTagRequest) error {

	_, err := s.tagRepository.CreateTag(ctx, req.Name)
	return err
}
func (s *tagService) DeleteTag(ctx context.Context, tagId uint) error {
	//查找标签在不在
	_, err := s.tagRepository.GetTagByID(ctx, tagId)
	if err != nil {
		return err
	}
	//查找标签是否被使用
	_, err = s.articleRepository.GetArticleTagByTagID(ctx, tagId)
	if err != nil {
		return err
	}
	err = s.articleRepository.DeleteArticleTagByTagID(ctx, tagId)
	err = s.tagRepository.DeleteTag(ctx, tagId)
	return err
}
